use "${hmrc_datadir}\ownership2\typecleaned.dta", clear
gen group=bvd_id if type=="uk_mnc_parent"|type=="uk_domestic_parent"|type=="standalone"
replace group=related_bvdid if (type=="domestic_uksubs"| type=="foreign_subs" | ///
type=="mnc_uksubs" | type=="uk_subs_unclassified") & relation=="global ultimate owner"
gsort bvd_id -group
bysort bvd_id: replace group=group[_n-1] if group=="" & group[_n-1]!=""
count if group==""
save "S:\DATALAB\Projects\Oxford - Transfer Pricing\Data\ownership2\typecleaned_group.dta", replace
use "S:\DATALAB\Projects\Oxford - Transfer Pricing\Data\ownership2\typecleaned_group.dta",clear
drop if group==""
keep type related_ctry relation bvd_id related_bvdid group
bysort bvd_id relation: gen n=1 if relation=="global ultimate owner"
bysort bvd_id relation: egen x=sum(n)
drop if x==2
keep bvd_id group
rename bvd_id identifier
duplicates drop
duplicates report identifier
duplicates tag identifier, gen (d)
drop if d!=0
drop d
save "${hmrc_datadir}\ownership2\groupid.dta", replace

use "${hmrc_datadir}\ownership2\groupid", clear
destring identifier, ignore("#", "*", "-") replace
destring group, ignore("#", "*", "-") replace
duplicates drop
duplicates tag id, gen (t)
drop if t!=0
drop t
save "${hmrc_datadir}\ownership2\groupid_clean", replace
